package com.yungui.leaning.entity;

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
        int[] nums = {2,1,5};
        sort(nums);
        System.out.println(Arrays.toString(nums));
    }
    public static void sort(int[] nums){
        int[] result = new int[nums.length];
        sort(nums,0,nums.length-1,result);
    }

    private static void sort(int[] nums, int left, int right, int[] result) {
        if (left<right){
            int mid = (left+right)/2;
            sort(nums,left,mid,result);
            sort(nums,mid+1,right,result);
            merge(nums,left,mid,right,result);
        }
    }

    private static void merge(int[] nums, int left, int mid, int right, int[] result) {
        int i=left;
        int j=mid+1;
        int t=0;
        while (i<=mid && j<=right){
            if (nums[i]<nums[j]){
                result[t++] = nums[i++];
            }else {
                result[t++] = nums[j++];
            }
        }
        while (i<=mid){
            result[t++] = nums[i++];
        }
        while (j<=right){
            result[t++] = nums[j++];
        }
        t=0;
        while (left<=right){
            nums[left++] = result[t++];
        }
    }

}
